import {setToken, getToken, removeToken } from '@/utils/auth'
import { login, getProfile } from '@/api/user'
const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  setToken(state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  // 设置用户信息
  setUserInfo(state, userInfo) {
    state.userInfo =  userInfo
  },
  // 删除用户信息
  reomveUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  // 退出登录的action
  logout(context) {
    context.commit('setToken', '') // 删除token
    context.commit('setUserInfo', {}) // 设置用户信息为空对象
  },
  async login(context, data) {
    const token = await login({password: data.password, mobile: data.mobile})
    console.log(token)
    context.commit('setToken', token)
  },
  // 用来获取用户信息的action
  async getUserInfo(context) {
    // ajax获取数据
    const rs = await getProfile()
    console.log('用来获取用户信息的,', rs)
    context.commit('setUserInfo', rs)
    return rs.roles
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}